# -*- coding: utf-8 -*-
# @Author  : Pony.guan
# @Time    : 2021/11/8 下午2:23
# Description: 服务相关配置

import os
import sys
import logging
from logging.handlers import TimedRotatingFileHandler

import redis
import netifaces
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from contextlib import contextmanager

BASE_DIR = os.path.dirname(os.path.abspath(__file__))


class CommonConfig:
    @staticmethod
    def get_log(debug):
        log_file = os.path.join(BASE_DIR, 'logs', 'log')
        log = logging.getLogger()
        log.setLevel(logging.DEBUG)
        formatter = logging.Formatter(
            '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')

        if debug:
            stream_handler = logging.StreamHandler(sys.stdout)
            stream_handler.setFormatter(formatter)
            log.addHandler(stream_handler)
        else:
            log_file_handler = TimedRotatingFileHandler(filename=log_file, when="D", interval=1, backupCount=7)
            log_file_handler.setFormatter(formatter)
            log_file_handler.setLevel(logging.DEBUG)
            log.addHandler(log_file_handler)
        return log


class ProductionConfig(CommonConfig):
    Debug = False
    mysql = {
        'host': '47.106.68.206',
        'port': 13306,
        'db': 'backend',
        'user': 'root',
        'passwd': 'root'
    }

    redis = {
        'host': '47.106.68.206',
        'port': 16379,
        'db': 0,
        'passwd': '123456'
    }

    def get_log(self):
        return super().get_log(self.Debug)


class DebugConfig(CommonConfig):
    Debug = True
    mysql = {
        'host': '127.0.0.1',
        'port': 13306,
        'db': 'backend',
        'user': 'root',
        'passwd': 'root'
    }

    redis = {
        'host': '127.0.0.1',
        'port': 16379,
        'db': 0,
        'passwd': '123456'
    }

    def get_log(self):
        return super().get_log(self.Debug)


ip_lst = [netifaces.ifaddresses(i).get(netifaces.AF_INET)[0]['addr'] for i in netifaces.interfaces() if
          netifaces.ifaddresses(i).get(netifaces.AF_INET)]

product_ip = '47.106.68.206'

if product_ip in ip_lst:
    Debug = False
    config = ProductionConfig()


else:
    Debug = True
    config = DebugConfig()

DB_CONNECT_STRING = 'mysql+pymysql://%(user)s:%(passwd)s@%(host)s:%(port)s/%(db)s?charset=utf8' % config.mysql

LOG = config.get_log()

# pool_recycle定期回收被mysql抛弃了的(过期)的session, 每次使用session都会判断是否过期
ENGINE = create_engine(DB_CONNECT_STRING, pool_recycle=3600, pool_pre_ping=True, pool_size=25)

DB_SESSION = sessionmaker(bind=ENGINE)

redis_pool = redis.ConnectionPool(host=config.redis['host'], port=config.redis['port'], db=config.redis['db'],
                                  password=config.redis['passwd'])
REDIS_CONN = redis.Redis(connection_pool=redis_pool)


@contextmanager
def SESSION_CONTEXT():
    session = DB_SESSION()
    try:
        yield session
        session.commit()
    except:
        session.rollback()
        raise
    finally:
        session.close()
